package com.facedemo.utils;

public class ReuseThread extends Thread {
    protected boolean isStopThread = true;
    protected boolean isRuning = false;
    protected boolean alreadyStart = false;

    /**
     * 线程是否运行中
     * @return true:线程运行中 false：线程未运行 或 线程空闲，等待中
     */
    public boolean nowRuning() {
        return isRuning;
    }

    //开始线程
    public void startThread() {
        if(isRuning) return;

        isRuning = true;
        isStopThread = false;

        if(alreadyStart) {
            synchronized (this) {
                this.notify();//唤醒等待的线程
            }
        } else {
            alreadyStart = true;
            this.start();
        }
    }

    //结束线程
    public void stopThread() {
        isStopThread = true;
        this.interrupt();//中断wait中的线程
    }

    @Override
    public void run() {
        super.run();
        while (!isStopThread) {
            work();
            try {
                synchronized (this) {
                    isRuning = false;
                    this.wait();
                }
            } catch (InterruptedException e) {
                LogUtils.printE("ReuseThread InterruptedException");
            }
        }
    }

    public void work() {
    }
}
